<?php

/*
Plugin Name: WP-Surveys
Plugin URI: http://wordpress.org/extend/plugins/wp-surveys
Description: Create Surveys for WordPress. Inspired by the groundwork of Survey Fly, which it was previously inspired by Instinct Entertainment's Survey Creator Plugin. That give me the base to do these modifications and have a new great plug-in! Thanks out to them for letting me use their code. Some features: Create, modify and retire surveys; Up to ten answer option with horizontal, vertical and dropdown-menu alignment; Backward compatibility with Polyglot plugin; Spanish and Basque localization.

Version: 0.8.3
Author: Martin Mozos, then Nielo Wait.
*/

/*  
Copyright 2008 Martin Mozos (email: martinmozos AT gmail DOT com)

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.

For a copy of the GNU General Public License, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
http://www.gnu.org/licenses/gpl.html
*/

/*******************************************************************************************************/
global $table_prefix, $wpdb;
$wp_surveys_tables = array(
	'survey' => $table_prefix . "surveys",
	'survey_meta' => $table_prefix . "surveys_meta",
	'question' => $table_prefix . "surveys_questions", 
	'answer' => $table_prefix . "surveys_answers",
	'response' => $table_prefix . "surveys_responses",
	'response_data' => $table_prefix . "surveys_response_data",
	'user' => $table_prefix . "users",
);

//$wpdb->show_errors();

$filePath = str_replace("\\", "/", dirname(__FILE__));

define('SURVEYS_FILE_PATH', str_replace("/includes", "", $filePath));
define('SURVEYS_DIR_NAME', str_replace("\\", "/", basename(SURVEYS_FILE_PATH)));

$siteurl = get_option('siteurl');

if (stristr(php_uname('s'), 'windows')) {
	$absPath = str_replace("\\", "/", ABSPATH);
} else {
	$absPath = ABSPATH;
}
define('SURVEYS_URL', str_replace($absPath, $siteurl."/",  SURVEYS_FILE_PATH));
define('SURVEYS_ABS_URL_PATH', str_replace($siteurl, "",  SURVEYS_URL));

if ( file_exists(ABSPATH . PLUGINDIR . '/polyglot.php') ) {
	$current_plugins = get_option('active_plugins');
	if (in_array('polyglot.php', $current_plugins)) {
		require_once(ABSPATH . PLUGINDIR . '/polyglot.php');
		polyglot_init();
	}
}

include_once('includes/survey_meta.php');

load_plugin_textdomain('wp-surveys',$path='wp-content/plugins/wp-surveys'); 

// ----------------------------------------------------------------
register_activation_hook(__FILE__, 'surveys_install');

add_filter('the_content', 'view_survey');
add_action('admin_menu', 'surveys_admin_page');
//add_filter('admin_head', 'admin_header');
//add_action('wp_head', 'plugin_header');
add_action('init', 'wpsurv_submit_survey');
// ----------------------------------------------------------------

function view_survey($content = '') {
	global $wp_surveys_tables, $wpdb;

	$re = '/<!-- wp_surveys id="(?<survey_id>\w+)" -->/';

	if ( preg_match($re, $content, $m) != 0 ) {
		$survey_id = $m['survey_id'];

//		ob_start();
		require_once("wp-surveys-out.php");
//		$output = ob_get_contents();
//		ob_end_clean();

		$content = preg_replace('/<!-- wp_surveys id="'.$survey_id.'" -->/', output_survey($survey_id), $content);
		$content = preg_replace('/<!-- wp_surveys default-css -->/', output_default_css(), $content);
		$content = preg_replace('/<!-- wp_surveys stepwise -->/', output_stepwise(), $content);
		
		return $content; 
	} else {
		return $content;
	}
}
 
function surveys_admin_page() {
//	global $table_prefix, $wpdb;
//	$wp_surveys_tables['survey'] = $table_prefix . "surveys";
//	$wpdb->query('update '.$wp_surveys_tables['survey'].' set blog_id=1;');
	if(function_exists('add_menu_page')) {
		$page = add_menu_page(__('Surveys', 'wp-surveys'), __('Surveys', 'wp-surveys'), 2, __FILE__, 'manage_surveys');
		add_action('admin_print_scripts-'.$page, 'surveys_admin_print_scripts');
		add_action('load-'.$page, 'surveys_process_data_requests');
	}
}

function surveys_process_data_requests(){
	require_once('functions.php');
	if($_POST["wpsurv_submit"] == __('CSV', 'wp-surveys'))
		results_CSV($_POST['survey_id']);    			
}

function surveys_admin_print_scripts() {
	global $wp_surveys_tables;
	wp_register_script('wp-surveys', SURVEYS_ABS_URL_PATH . '/js/wp-surveys.js');
	wp_print_scripts('wp-surveys');	
	wp_register_script('jquery.wysiwyg', SURVEYS_ABS_URL_PATH . '/js/jquery.wysiwyg.js', array('jquery'));
	wp_print_scripts('jquery.wysiwyg');	
	wp_register_style('jquery.wysiwyg', SURVEYS_ABS_URL_PATH . '/css/jquery.wysiwyg.css');
	wp_print_styles('jquery.wysiwyg');
?>
	<script type="text/javascript">
		jQuery(document).ready(function() {
			jQuery('textarea').each(function(){
				if (jQuery(this).attr('id') != 'wp_surveys_report_template') {
					jQuery(this).wysiwyg();
				}
			});
		});
	</script>	
<?php
}

/*
function admin_header() {
	if(substr(($_REQUEST[page]), 0, 10) == 'wp-surveys') {
		echo	'<style type="text/css">\n
					</style>';
		}
		return;
	}

function plugin_header() { ?>
	<style type="text/css" media="screen">
	</style><?php
   }
*/
function wpsurv_submit_survey() {
	global $wpdb, $current_user, $wp_surveys_tables;
	
	session_start();

	$_SESSION['voted'] = false;
	$_SESSION['novote'] = false;

    if(($_POST['wpsurveys_button'] == __('Submit Survey', 'wp-surveys')) && is_numeric($_POST['survey_id'])) {
		$survey_id = $_POST['survey_id'];
		$unique_id = md5(uniqid(rand(), true));
		$questions = $wpdb->get_results("SELECT distinct * FROM `".$wp_surveys_tables['question']."` WHERE `survey_id`=".$survey_id.";",ARRAY_A);

		if($questions) {
			foreach($questions as $question) {
				if (!$_POST['answer_'.$question['question_id']]) {
					$_SESSION['novote'] = true;
					session_write_close();
					return;
				}
			}
		}
		
		$wpdb->query("INSERT INTO `".$wp_surveys_tables['response']."` (`user_id`, `survey_id`, `response_unique_id`, `response_datestamp`) VALUES (".$current_user->ID.", '".$survey_id."', '".$unique_id."', '".gmdate("Y-m-d H:i:s", time())."');");
		$response_id = $wpdb->get_var("SELECT `response_id` FROM `".$wp_surveys_tables['response']."` WHERE `response_unique_id`='".$unique_id."' LIMIT 1;");
		foreach ($questions as $question) {
			//This will become more complex as more answer types get added.
			$wpdb->query("INSERT INTO `".$wp_surveys_tables['response_data']."` (`response_id`, `survey_id`, `question_id`, `answer_id`) VALUES (".$response_id.", '".$survey_id."', '".$question['question_id']."', '".$_POST['answer_'.$question['question_id']]."');");
		}
		$survey_repost = $wpdb->get_var("SELECT `survey_repost` FROM `".$wp_surveys_tables['survey']."` WHERE `survey_id`=".$survey_id." LIMIT 1;");
		$expiry = gmmktime()+(60 * 60 * 24 * $survey_repost);
		//$expiry = gmmktime() + 60; // expires in 60 seconds for testing
		setcookie("voted[survey_id]", $survey_id, $expiry);
		setcookie("voted[unique_id]", $unique_id, $expiry);
		$_SESSION['voted'] = true;
		$_SESSION['response_id'] = $response_id;
	}
	session_write_close();
}
 
function manage_surveys() {
	global $wpdb, $blog_id, $wp_surveys_tables;
	if(isset($_REQUEST["wpsurv_submit"])) {
		require_once('functions.php');
	 	if(($_POST["wpsurv_submit"] == __('Edit', 'wp-surveys')) || ($_POST["wpsurv_submit"] == __('Cancel', 'wp-surveys')) || ($_POST["wpsurv_submit"] == __('Back to Edit Survey', 'wp-surveys')))
			edit($_POST['survey_id']);
	    elseif($_POST["wpsurv_submit"] == __('Update', 'wp-surveys'))
			update($_POST['survey_id']);
		elseif($_POST["wpsurv_submit"] == __('Update Answers', 'wp-surveys'))
			update_answers($_POST['survey_id'], $_POST['question_id']);
		elseif(($_POST["wpsurv_submit"] == __('Activate', 'wp-surveys')) || ($_POST["wpsurv_submit"] == __('Make Active', 'wp-surveys')))
			activate($_POST['survey_id']);
		elseif($_POST["wpsurv_submit"] == __('Retire', 'wp-surveys'))
			retire($_POST['survey_id']);
		elseif(($_POST["wpsurv_submit"] == __('Edit Answers', 'wp-surveys')) || ($_POST["wpsurv_submit"] == __('Add Some Answers', 'wp-surveys')) || ($_POST["wpsurv_submit"] == __('Edit or Add more Answers', 'wp-surveys')))
			edit_answers($_POST['survey_id'], $_POST['question_id']);
		elseif(($_POST["wpsurv_submit"] == __('Add More Questions', 'wp-surveys')) || ($_POST["wpsurv_submit"] == __('Add Some Questions', 'wp-surveys')))
			add_question($_POST['survey_id']);
  		elseif($_POST["wpsurv_submit"] == __('Step 2', 'wp-surveys'))
			step2($_POST['survey_id']);
		elseif($_POST["wpsurv_submit"] == __('Create Question', 'wp-surveys'))
			create_question($_POST['survey_id']);
  		elseif(($_POST["wpsurv_submit"] == __('Change Survey', 'wp-surveys')) || ($_POST["wpsurv_submit"] == __('Add Survey', 'wp-surveys')))
			survey($_POST['survey_id']);
  		elseif($_POST["wpsurv_submit"] == __('Add This Survey', 'wp-surveys')) 
			add_survey($_POST['survey_id']);
		elseif($_POST["wpsurv_submit"] == __('Result Summary', 'wp-surveys'))
			results($_POST['survey_id']);
//		elseif($_POST["wpsurv_submit"] == __('CSV', 'wp-surveys'))
//			results_CSV($_POST['survey_id']);    			
//   	elseif($_POST["wpsurv_submit"] == __('Delete File', 'wp-surveys'))
//			delete_file($_POST['survey_id']);
	} else {
		$current_plugins = get_option('active_plugins');
		if ((file_exists(ABSPATH . PLUGINDIR . '/polyglot.php')) && (in_array('polyglot.php', $current_plugins)))
			$polyglot = true;
		$open_surveys = $wpdb->get_results("SELECT * FROM `".$wp_surveys_tables['survey']."` WHERE `survey_open`='1' and blog_id=".$blog_id.";",ARRAY_A);
?>
	<div class="wrap">
		<h2><?php echo __('Survey Management', 'wp-surveys');?></h2>
		<h3><u><?php echo __('Active Surveys', 'wp-surveys');?></u>:</h3>
<?php
		if($open_surveys) {
?>
		<table class="widefat" width="100%" cellpadding="4" cellspacing="4">
			<tr>
				<th align="left"><?php echo __('Title', 'wp-surveys');?></th>
				<th align="left"><?php echo __('Description', 'wp-surveys');?></th>
				<th></th>
				<th></th>
				<th></th>
				<th></th>
				<th></th>
			</tr>
<?php
			foreach($open_surveys as $survey) {
?>
			<tr class="alternate">
<?php
				if($polyglot) {
?>
				<td>
					<b><?php echo polyglot_filter(stripcslashes($survey['survey_name']));?></b>
				</td>
				<td>
					<?php echo polyglot_filter(stripcslashes($survey['survey_describe']));?>
				</td>
<?php
				} elseif(!$polyglot) {
?>
				<td>
					<b><?php echo stripcslashes($survey['survey_name']);?></b>
				</td>
				<td>
					<?php echo stripcslashes($survey['survey_describe']);?>
				</td>
<?php
				}
?>
				<td class="submit" align="center">
					<form method="post" action="">
						<input type="hidden" name="survey_id" value="<?php echo $survey['survey_id'];?>" />
						<input type="submit" name="wpsurv_submit" value="<?php echo __('Edit', 'wp-surveys');?>" />
					</form>
				</td>
				
				<td class="submit" align="center">
					<form method="post" action="">
						<input type="hidden" name="survey_id" value="<?php echo $survey['survey_id'];?>" />
						<input type="submit" name="wpsurv_submit" value="<?php echo __('Retire', 'wp-surveys');?>" />
					</form>
				</td>
				
				<td class="submit" align="center">
					<form method="post" action="">
						<input type="button" onClick="toggle_code(this, <?php echo $survey['survey_id'];?>, '<?php echo __('View Code', 'wp-surveys');?>', '<?php echo __('Hide Code', 'wp-surveys');?>')" name="wpsurv_submit" value="<?php echo __('View Code', 'wp-surveys');?>" title="<?php echo __('Displays the code that needs to be placed in the source of a page or post in order to include this specific suvey on said page or post.', 'wp-surveys');?>"/>
						<div id="code_view_<?php echo $survey['survey_id'];?>" style="display:none;">1</div>
					</form>
				</td>
				
				<td class="submit" align="center">
					<form method="post" action="">
						<input type="hidden" name="survey_id" value="<?php echo $survey['survey_id'];?>" />
						<input type="submit" name="wpsurv_submit" value="<?php echo __('Result Summary', 'wp-surveys');?>" />
					</form>
				</td>
				
				<td class="submit" align="center">
					<form method="post" action="">
						<input type="hidden" name="survey_id" value="<?php echo $survey['survey_id'];?>" />
						<input type="submit" name="wpsurv_submit" value="<?php echo __('CSV', 'wp-surveys');?>" />
					</form>
				</td>
<?php
				//echo '<td align="center"><form method="post" action=""><input type="hidden" name="survey_id" value="'.$survey['survey_id'].'" />';
				//echo '<input type="submit" name="wpsurv_submit" value="'.__('View Survey Results in CSV File', 'wp-surveys').'" /></form></td>';
?>
			</tr>
<?php
				}
?>
		</table>
<?php
			$next = ++$survey['survey_id'];
?>

		<br />
		<form method="post" action="">
			<input type="hidden" name="survey_id" value="<?php echo $next;?>" />
			<input class="button" type="submit" name="wpsurv_submit" value="<?php echo __('Add Survey', 'wp-surveys');?>" />
		</form>
<?php
		} else {
?>
		<?php echo __('There are no open surveys', 'wp-surveys');?>.
<?php
			//$last = $wpdb->get_var("SELECT COUNT(`survey_id`) FROM `".$wp_surveys_tables['survey']."`;");
			$last = $wpdb->get_var("SELECT `survey_id` FROM `".$wp_surveys_tables['survey']."` ORDER BY `survey_id` DESC LIMIT 1;");
			$next = ++$last;
?>
		<br />
		<br />
		<form method="post" action="">
			<input type="hidden" name="survey_id" value="<?php echo $next;?> " />
			<input class="button" type="submit" name="wpsurv_submit" value="<?php echo __('Add Survey', 'wp-surveys');?>" />
		</form>
<?php
		}
		$closed_surveys = $wpdb->get_results("SELECT * FROM `".$wp_surveys_tables['survey']."` WHERE `survey_open`='0' and blog_id=".$blog_id.";",ARRAY_A);
?>
		<h3><u><?php echo __('Retired Surveys', 'wp-surveys');?></u>:</h3>
<?php
		if($closed_surveys) {
?>
		<table class="widefat" width="100%" cellpadding="4" cellspacing="4">
			<tr>
				<th align="left"><?php echo __('Title', 'wp-surveys');?></th>
				<th align="left"><?php echo __('Description', 'wp-surveys');?></th>
				<th></th>
				<th></th>
				<th></th>
				<th></th>
			</tr>
<?php
			foreach($closed_surveys as $survey) {
?>
			<tr class="alternate">
<?php
				if($polyglot) {
?>
				<td>
					<b><?php echo polyglot_filter(stripcslashes($survey['survey_name']));?></b>
				</td>
				<td>
					<?php echo polyglot_filter(stripcslashes($survey['survey_describe']));?>
				</td>
<?php
				} elseif(!$polyglot) {
?>
				<td>
					<b><?php echo stripcslashes($survey['survey_name']);?></b>
				</td>
				<td>
					<?php echo stripcslashes($survey['survey_describe']);?>
				</td>
<?php
				}
?>
				<td class="submit" align="center">
					<form method="post" action="">
						<input type="hidden" name="survey_id" value="<?php echo $survey['survey_id'];?>" />
						<input type="submit" name="wpsurv_submit" value="<?php echo __('Edit', 'wp-surveys');?>" />
					</form>
				</td>
				
				<td class="submit" align="center">
					<form method="post" action="">
						<input type="hidden" name="survey_id" value="<?php echo $survey['survey_id'];?>" />
						<input type="submit" name="wpsurv_submit" value="<?php echo __('Make Active', 'wp-surveys');?>" />
					</form>
				</td>
				
				<td class="submit" align="center">
					<form method="post" action="">
						<input type="hidden" name="survey_id" value="<?php echo $survey['survey_id'];?>" />
						<input type="submit" name="wpsurv_submit" value="<?php echo __('Result Summary', 'wp-surveys');?>" />
					</form>
				</td>
				
				<td class="submit" align="center">
					<form method="post" action="">
						<input type="hidden" name="survey_id" value="<?php echo $survey['survey_id'];?>" />
						<input type="submit" name="wpsurv_submit" value="<?php echo __('CSV', 'wp-surveys');?>" />
					</form>
				</td>
<?php
				//echo '<td align="center"><form method="post" action=""><input type="hidden" name="survey_id" value="'.$survey['survey_id'].'" />';
				//echo '<input type="submit" name="wpsurv_submit" value="'.__('View Survey Results in CSV File', 'wp-surveys').'" /></form></td>';
?>
			</tr>
<?php
			}
?>
		</table>
<?php
		} else {
?>
		<?php echo __('There are no retired surveys', 'wp-surveys');?>.
<?php
		}
?>
	</div>
<?php
	}
}
	
function surveys_install() {
	global $wpdb, $wp_surveys_tables;

/*
 * When needing to force a clean db; 
 */

/*
	$tables = array($wp_surveys_tables['survey'], $wp_surveys_tables['survey_meta'], $wp_surveys_tables['question'], $wp_surveys_tables['answer'], $wp_surveys_tables['response'], $wp_surveys_tables['response_data']);
	foreach ($tables as $table) {
		$sql = "DROP TABLE `".$table."`;";
		$wpdb->query($sql);
	}
*/
	if($wpdb->get_var("SHOW TABLES LIKE '".$wp_surveys_tables['survey']."'") != $wp_surveys_tables['survey']) {
		$sql = "CREATE TABLE `".$wp_surveys_tables['survey']."` (".
		"`survey_id` bigint(16) unsigned NOT NULL auto_increment,".
		"`blog_id` bigint(16) unsigned,".
		"`user_id` bigint(16) unsigned NOT NULL,".
		"`survey_name` varchar(255) NOT NULL,".
		"`survey_describe` text,".
		"`survey_open` bigint(16) NOT NULL default '0',".
		"`survey_repost` bigint(16) NOT NULL default '90',".
		"`survey_page_chain` text NOT NULL,".
		"`survey_redirect_URL` text NOT NULL,".
		"`survey_share_results` bigint(16) NOT NULL default '0',".
		"PRIMARY KEY (`survey_id`)) DEFAULT CHARACTER SET utf8;";
		$wpdb->query($sql);
	}

	if($wpdb->get_var("SHOW TABLES LIKE '".$wp_surveys_tables['survey_meta']."'") != $wp_surveys_tables['survey_meta']) {
		$sql = "CREATE TABLE `".$wp_surveys_tables['survey_meta']."` (".
		"`survey_meta_id` bigint unsigned NOT NULL auto_increment,".
		"`survey_id` bigint unsigned NOT NULL,".    
		"`meta_key` varchar (256) NOT NULL,".
		"`meta_value` text NOT NULL,".
		"PRIMARY KEY (`survey_meta_id`)) DEFAULT CHARACTER SET utf8;";
		$wpdb->query($sql);
	}

	if($wpdb->get_var("SHOW TABLES LIKE '".$wp_surveys_tables['question']."'") != $wp_surveys_tables['question']) {
		$sql = "CREATE TABLE `".$wp_surveys_tables['question']."` (".
		"`question_id` bigint unsigned NOT NULL auto_increment,".
		"`question_text` text NOT NULL,".
		"`question_type` varchar( 128 ) NOT NULL,".
		"`question_group` varchar( 128 ),".
		"`question_weight` varchar( 128 ),".
		"`question_rows` bigint(16) NOT NULL default '1',".
		"`survey_id` bigint unsigned NOT NULL,".    
		"`question_forever` text NOT NULL,".
		"`question_manditory` bigint(16) NOT NULL default '0',".
		"PRIMARY KEY (`question_id`)) DEFAULT CHARACTER SET utf8;";
		$wpdb->query($sql);
	}

	if($wpdb->get_var("SHOW TABLES LIKE '".$wp_surveys_tables['answer']."'") != $wp_surveys_tables['answer']) {
		$sql = "CREATE TABLE `".$wp_surveys_tables['answer']."` (".
		"`answer_id` bigint unsigned NOT NULL auto_increment,".
		"`answer_text` text NOT NULL,".
		"`answer_weight` varchar( 128 ) NOT NULL,".
		"`survey_id` bigint unsigned NOT NULL,".    
		"`question_id` bigint unsigned NOT NULL,".    
		"PRIMARY KEY (`answer_id`)) DEFAULT CHARACTER SET utf8;";
		$wpdb->query($sql);
	}

	if($wpdb->get_var("SHOW TABLES LIKE '".$wp_surveys_tables['response']."'") != $wp_surveys_tables['response']) {
		$sql = "CREATE TABLE `".$wp_surveys_tables['response']."` (".
		"`response_id` bigint unsigned NOT NULL auto_increment,".
		"`response_unique_id` varchar( 128 ) NOT NULL,".
		"`response_datestamp` datetime NOT NULL default '0000-00-00 00:00:00',".
		"`user_id` bigint(16) unsigned NOT NULL,".
		"`survey_id` bigint unsigned NOT NULL,".    
		"PRIMARY KEY (`response_id`)) DEFAULT CHARACTER SET utf8;";
		$wpdb->query($sql);
	}
	
	if($wpdb->get_var("SHOW TABLES LIKE '".$wp_surveys_tables['response_data']."'") != $wp_surveys_tables['response_data']) {
		$sql = "CREATE TABLE `".$wp_surveys_tables['response_data']."` (".
		"`data_id` bigint unsigned NOT NULL auto_increment,".
		"`response_id` bigint unsigned NOT NULL,".
		"`survey_id` bigint unsigned NOT NULL,".    
		"`question_id` bigint unsigned NOT NULL,".    
		"`answer_id` bigint unsigned NOT NULL,".    
		"`data` text NOT NULL,".
		"PRIMARY KEY (`data_id`)) DEFAULT CHARACTER SET utf8;";
		$wpdb->query($sql);
	}

//	require_once("mbb.php");
} 

?>
